﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SMS
{
    public partial class SMSPrinter : Form
    {
        private StringBuilder StringBuild;
        private bool m_bDirty;
        private bool m_bIsWatching;
        private StreamReader sr;
        private Font verdana10Font;
        public String FilePathName =System.Configuration.ConfigurationSettings.AppSettings["FilePathName"];//=@"C:\tvc-cards\out\";
        public string Log = System.Configuration.ConfigurationSettings.AppSettings["log"];//= @"C:\tvc-cards\log";        
        public String path ;// = @"C:\tvc-cards\template\";
        public String Archive = System.Configuration.ConfigurationSettings.AppSettings["Archive"]; //= @"C:\tvc-cards\archive\";
        public StreamWriter SW ;
        public bool Printer = false ;
        public string strDatetime ;
        string AcrobatPath = System.Configuration.ConfigurationSettings.AppSettings["AcrobatReader"];
        
       public int Sleep = Int16.Parse(System.Configuration.ConfigurationSettings.AppSettings["Sleep"]);
        
        public SMSPrinter()
        {
            InitializeComponent();
            //btnStart.Enabled = false;
            StringBuild = new StringBuilder();
            m_bDirty = false;
            m_bIsWatching = false;
         bool   FileExist = false;

         if (!File.Exists(AcrobatPath))
         {
             MessageBox.Show("Please Eneter valid Acrobat Path in App.Config File");

         }
         else
         {
             FileExist = true;
         }

         if (!Directory.Exists(Archive))
         {
             MessageBox.Show("Please Enter a Valid Archive Path in App.config File");
         }
         else
         {
             FileExist = true;
         }

         if (!Directory.Exists(Log))
         {
             MessageBox.Show("Please Enter a Valid log Path in App.config File");

         }
         else
         {
             FileExist = true;

         }
            strDatetime = DateTime.Now.GetDateTimeFormats()[28].ToString().Replace(":", "_");                   
        }
      
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_bIsWatching)
                {
                    btnStart.BackColor = Color.LightSkyBlue;
                    btnStart.Text = "Start Watching";
                    lbltext.Text = "To Start the Application Click on Start Button";
                    SW.WriteLine(string.Empty);
                    SW.WriteLine("Application Stoped : " + DateTime.Now.ToString());
                    SW.WriteLine("--------------------The End--------------------");
                    //SW.Close();
                }
                else
                {
                    Printer = true;
                    string Logpath = Log + "\\" + strDatetime + ".txt";
                    SW = File.CreateText(Logpath);
                    m_bIsWatching = true;
                    btnStart.BackColor = Color.Red;
                    btnStart.Text = "Stop Watching";
                    lbltext.Text = "To Stop the Application Click on Stop Button";
                    SW.WriteLine("Application Started : " + DateTime.Now.ToString());
                    SW.WriteLine(string.Empty);
                }
            }
            catch (Exception Ex)
            {
                SW.WriteLine(Ex.Message.ToString());
            }
        }

        public void Print_output()
        {
            try
            {

                if (btnStart.Text != "Start Watching")
                {
                    string[] FILES = Directory.GetFiles(FilePathName);
                    if (FILES.Length > 0)
                    {
                        if (FILES[0] != null)
                        {
                        }

                        foreach (string subfiles in FILES)
                        {
                            this.GenerateXML(subfiles, "exist");
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                SW.WriteLine(Ex.Message.ToString());
            }
        }

        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            try
            {
                if (!m_bDirty)
                {
                    StringBuild.Remove(0, StringBuild.Length);
                    StringBuild.Append(e.FullPath);
                    StringBuild.Append(" ");
                    StringBuild.Append(e.ChangeType.ToString());
                    StringBuild.Append("    ");
                    StringBuild.Append(DateTime.Now.ToString());
                    m_bDirty = true;
                    this.GenerateXML(e.FullPath, StringBuild.ToString());
                }
            }
            catch (Exception ex)
            {
                SW.WriteLine(ex.Message.ToString());
            }
        }

        private void tmrEditNotify_Tick(object sender, EventArgs e)
        {
            if (Printer)
            {
                Print_output();
            }
        }

        private void GenerateXML(string pStrFpath, string pStrMsg)
        {
            FileInfo lObjFInfo = null;

            try
            {
                lObjFInfo = new FileInfo(pStrFpath);

                if (lObjFInfo.Exists)
                {
                    if (lObjFInfo.Extension.Equals(".pdf"))
                    {
                        if (lObjFInfo.Length > 0)
                        {
                            if (this.ProcessFileContent(lObjFInfo, pStrMsg))
                            {
                                SW.WriteLine("GOING FOR PRINTOUT");
                            }
                            this.BackUpFile(lObjFInfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SW.WriteLine(ex.Message.ToString());
                throw ex;
            }
            finally
            {
                try
                {

                    if (lObjFInfo.Extension.Equals(".pdf"))
                    {
                        lObjFInfo.Delete();
                    }
                }
                catch (Exception ex)
                {

                    Thread.Sleep(1000);
                    lObjFInfo.Delete();
                    SW.WriteLine(ex.Message.ToString());

                }
            }
        }

        private void RunExecutable(string executable, string arguments)
        {
            try
            {
                
                ProcessStartInfo starter = new ProcessStartInfo(executable, arguments);
                starter.CreateNoWindow = true;
                starter.RedirectStandardOutput = true;
                starter.UseShellExecute = false;
                Process process = new Process();
                process.StartInfo = starter;
                process.Start();
                StringBuilder buffer = new StringBuilder();
                using (StreamReader reader = process.StandardOutput)
                {
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        buffer.Append(line);
                        buffer.Append(Environment.NewLine);
                        line = reader.ReadLine();
                        Thread.Sleep(Sleep);
                        
                    }
                }
            }
            catch (Exception ex)
            {
                SW.WriteLine(ex.Message.ToString()); 
            }
        }

        private bool ProcessFileContent(FileInfo pObjFInfo, string pStrBodyMsg)
        {
            bool blnProcessStatus = false;
            //string BookingNum = string.Empty;
            try
            {
                SW.WriteLine(pObjFInfo.Name + " Printed at :" + DateTime.Now.ToString());
                Process proc = new Process();
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                proc.StartInfo.Verb = "print";
                string pdfFileName = pObjFInfo.ToString();
                //proc.StartInfo.FileName = @"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe";
                proc.StartInfo.FileName = AcrobatPath;
                SW.WriteLine(AcrobatPath);
                proc.StartInfo.Arguments = @"/p /h /t " + pObjFInfo.ToString();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                SW.WriteLine("pdf opened");
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                if (proc.HasExited == false)
                {
                    proc.WaitForExit(10000);
                    //proc.Kill();
                }
                proc.EnableRaisingEvents = true;
                // AcroRd32.exe
                proc.CloseMainWindow();
                SW.WriteLine("pdf closed");
                proc.Close();

            }
            catch (Exception ex)
            {
                SW.WriteLine(ex.Message.ToString());
            }
            return blnProcessStatus;
        }

        private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
        {
            try
            {
                //Get the Graphics object
                Graphics g = ppeArgs.Graphics;
                float linesPerPage = 0;
                float yPos = 0;
                int count = 0;
                //Read margins from PrintPageEventArgs
                float leftMargin = ppeArgs.MarginBounds.Left;
                float topMargin = ppeArgs.MarginBounds.Top;
                string line = null;
                //Calculate the lines per page on the basis of the height of the page and the height of the font
                linesPerPage = ppeArgs.MarginBounds.Height /
                verdana10Font.GetHeight(g);
                //Now read lines one by one, using StreamReader
                while (count < linesPerPage &&
                ((line = sr.ReadLine()) != null))
                {
                    //Calculate the starting position
                    yPos = topMargin + (count *
                    verdana10Font.GetHeight(g));
                    //Draw text
                    g.DrawString(line, verdana10Font, Brushes.Black,
                    leftMargin, yPos, new StringFormat());
                    //Move to next line
                    count++;
                }
                //If PrintPageEventArgs has more pages to print
                if (line != null)
                {
                    ppeArgs.HasMorePages = true;
                }
                else
                {
                    ppeArgs.HasMorePages = false;
                }
            }
            catch (Exception Ex)
            {
                SW.WriteLine(Ex.Message.ToString());

            }
        }

        private void BackUpFile(FileInfo pObjFInfo)
        {
            string lStrBackupFName = pObjFInfo.Name;
            string lStrFldName = this.GetValueFromConfig("Backup");
            pObjFInfo.CopyTo(lStrFldName + lStrBackupFName, true);
        }

        private string GetValueFromConfig(string pObjGetKey)
        {
            // return ConfigurationManager.AppSettings[pObjGetKey].ToString();
            return Archive;
        }

        //private void btnBrowse_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        if (fbdOut.ShowDialog() == DialogResult.OK)
        //        {
        //            //if (fbdOut.SelectedPath.Contains("out"))
        //            //{
        //                txtBrowse.Text = fbdOut.SelectedPath;//this variable gives the name of selected file
        //                //Archive = fbdOut.SelectedPath.Replace("out", @"archive\");
        //                //Log = fbdOut.SelectedPath.Replace("out", "log");
        //                //path = fbdOut.SelectedPath.Replace("out", @"template\");
        //                FilePathName = txtBrowse.Text;
        //                btnStart.Enabled = true;
        //                //StreamReader srpath = new StreamReader(path + "path.txt");
        //                //srpath.Read();
        //                //AcrobatPath = srpath.ReadLine();
        //            //}
        //            //else
        //            //{
        //            //    MessageBox.Show("Please Select the Out File Directory");
        //            //}
        //        }
        //    }
        //    catch (Exception Ex)
        //    {
        //        SW.WriteLine(Ex.Message.ToString());
        //    }
        //}


     
    }
}
